package com.atguigu.srb.core.controller.admin;


import com.alibaba.excel.EasyExcel;
import com.atguigu.srb.common.result.R;
import com.atguigu.srb.core.pojo.dto.ExcelDictDTO;
import com.atguigu.srb.core.pojo.entity.Dict;
import com.atguigu.srb.core.service.DictService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * <p>
 * 数据字典 前端控制器
 * </p>
 *
 * @author Mr.bilal
 * @since 2023-07-18
 */
@RestController
@RequestMapping("/admin/core/dict")
@Api(tags = "数据字典")
@Slf4j
@CrossOrigin
public class AdminDictController {

    @Autowired
    DictService dictService;

    @PostMapping("/import")
    @ApiOperation("文件上传")
    public R importDictExcel(@RequestParam("file")MultipartFile multipartFile){
        dictService.importDictExcel(multipartFile);
        return R.ok();
    }

    @GetMapping("/export")
    @ApiOperation("文件上传")
    public void exportDictExcel(HttpServletResponse response){
        List<ExcelDictDTO> excelDictDTOS = dictService.exportDictExcel();
        try {
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/vnd.ms-excel");
            String fileName = URLEncoder.encode("mydict", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream()).sheet("数据字典").doWrite(excelDictDTOS);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    @GetMapping("/getDictListByParentId/{parentId}")
    public R getDictListByParentId(@PathVariable("parentId") Long parentId){
        List<Dict> list = dictService.getDictListByParentId(parentId);
        return R.ok().data("list",list);
    }

}

